package com.dongdongqiang.daogenerator.handler.impl;

import com.dongdongqiang.daogenerator.exception.DDQException;
import com.dongdongqiang.daogenerator.handler.IInsertHandler;
import com.dongdongqiang.daogenerator.pojo.TableMeta;
import com.dongdongqiang.daogenerator.sqlbuilder.InsertSQLBuilder;
import com.dongdongqiang.daogenerator.statement.IInsertPrepareStatementSetter;
import com.dongdongqiang.daogenerator.tablemetabuilder.TableMetaBuilderImpl;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by ZZB on 2017/10/8.
 */
public class InsertHandlerImpl implements IInsertHandler {
    private InsertSQLBuilder insertSQLBuilder;
    private IInsertPrepareStatementSetter insertPrepareStatementSetter;

    public InsertHandlerImpl(InsertSQLBuilder insertSQLBuilder, IInsertPrepareStatementSetter insertPrepareStatementSetter) {
        this.insertSQLBuilder = insertSQLBuilder;
        this.insertPrepareStatementSetter = insertPrepareStatementSetter;
    }

    @Override
    public int insert(Object o, Connection connection) throws DDQException {
        TableMeta tableMeta = TableMetaBuilderImpl.obtainByObject(o);
        String insertSQL = insertSQLBuilder.buildInsertSQL(tableMeta);
        if(insertSQL == null) return 0;
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(insertSQL);
            insertPrepareStatementSetter.setInPrepareStatement(preparedStatement, tableMeta, o);
            return preparedStatement.executeUpdate();
        } catch (SQLException | InvocationTargetException | IllegalAccessException | NoSuchMethodException | NoSuchFieldException e) {
            throw new DDQException(e);
        }
    }

    @Override
    public int[] insertList(List<?> objects, Connection connection) throws DDQException {
        TableMeta tableMeta = TableMetaBuilderImpl.obtainByObject(objects.get(0));
        String insertSQL = insertSQLBuilder.buildInsertSQL(tableMeta);
        if(insertSQL == null) return new int[]{0};
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(insertSQL);
            insertPrepareStatementSetter.setBatchInPrepareStatement(preparedStatement, tableMeta, objects);
            return preparedStatement.executeBatch();
        } catch (SQLException | NoSuchMethodException | NoSuchFieldException | IllegalAccessException | InvocationTargetException e) {
            throw new DDQException(e);
        }
    }
}
